<?php
declare(strict_types=1);
/**
 * @author hjj
 * 关务
 */
namespace Service\SupplierService\SupplierMapping;

use Service\Code\Normal;

class Shopcustom extends BaseMapping
{
    /**
     * 同步订单清关相应状态轨迹
     * @param array $param
     */
    public function orderLogistics( $param = [] )
    {
        return Normal::returnCode(Normal::SUC,"当前关务轨迹状态无须同步");
    }

    /**
     * 商品数据映射
     * @param $contents
     * @param array $hscodes
     * @return array
     */
    public function getGoodsMapping($contents, $hscodes,$supplier) {
        if (empty($contents['inventoryQtys'])) {
            return [];
        }
        $stock = [];
        $batchArr = [];
        foreach($contents['inventoryQtys'] as $batch){
            $batchArr[$batch['batchNo']][] = $batch;
        }
        
        //上架的批次
        $isDownBatchNo=[];
        foreach($batchArr as $k => $v)
        {
            $batch = reset($v);
            
            //如果是下架的直接删除该批次
            if($batch['isDown'] == true) {
                $isDownBatchNo[]=$k;
                unset($batchArr[$k]);
                continue;
            }
            
            $specsStr = trim($batch['specs']);
            $specsStr = trim($batch['specs'], ',');
            $specArr  = explode(',', $specsStr);
            $specArr  = array_filter(array_unique($specArr));
            $specList = [];
            if ($specArr) {
                sort($specArr);
                foreach ($specArr as $specNum) {
                    $price      = bcmul((string)$batch['onePiecePriceTax'], $specNum, 2);
                    $specList[] = [
                        'SpecificationNum'   => $specNum,
                        'SpecificationPrice' => $price,
                    ];
                }
            }
            $isHavePrice    = empty($batch['onePiecePriceTax']) ? 0 : 1;
            $number         = $batch['inventoryQuantity'];
            $isHasPrice     = $isHavePrice;

            //路由模式
            if($supplier['IsTryUpdateCommodityArchives'] == 1) {
                $number = 10000;
                $isHasPrice = 1;
            }
            
            $item = [
                $this->supplierStock->batchNo    => $batch['batchNo'],
                $this->supplierStock->number     => $number,
                $this->supplierStock->specList   => $specList,
                $this->supplierStock->isHasPrice => $isHasPrice, //是否有价格 1是 0无 //自营供应商路由模式默认库存
                $this->supplierStock->BatchID    => $batch['batchID'], //批次ID
            ];
            //判断效期是否为实际格式
            $isDataTime = $this->isDateTime($item['BatchNo']);
            if ($isDataTime) {
                $item[$this->supplierStock->isHasPeriodTime] = 1;
                $item[$this->supplierStock->periodTime]      = date('Y-m-d H:i:s', strtotime($item['BatchNo']));
            }
            $stock[] = $item;
        }
        //上游的上下架状态 1上 0下
        $upstreamSaleType = 1;
        if($supplier['IsTryUpdateCommodityArchives'] != 1 && $contents['tax'] <= 0){
            $upstreamSaleType = 0;
        }
        if (empty($contents['imageUrls'])) {
            $imagesUrl = [];
        } else {
            $originImgArr = json_decode($contents['imageUrls'], true);
            if (!empty($originImgArr)) {
                $imagesUrl = array_column($originImgArr, 'url');
            } else {
                $imagesUrl = [];
            }
        }
        
        //如果是通推模式下设置含税
        $isHaveTaxRate = 0;
        if( $supplier['IsOneByOneMakeArchiveDoc'] == 1 ) {
            $isHaveTaxRate = 1;
        }
        
        return [
            'base'  => [
                $this->supplierCommodity->description      => $contents['description'] ?? '', //商品描述
                $this->supplierCommodity->uinit            => $contents['goodsUnit']?? self::DEFAULT_Uinit, //没单位 给默认单位 007 个
                $this->supplierCommodity->brand            => $contents['goodsBrandName'] ?? self::DEFAULT_BRAND, //品牌
                $this->supplierCommodity->classify         => $contents['classifyName'] ?? self::DEFAULT_CLASSIFY, //分类名称
                $this->supplierCommodity->originPlace      => $contents['goodsOriginCountry'] ?? self::DEFAULT_ORIGINPLACE, //产地
                $this->supplierCommodity->barcode          => $contents['barCode'], //国际条码
                $this->supplierCommodity->goodstype        => 1, //商品类型  0一般 1保税 2海外
                $this->supplierCommodity->imageUrl         => json_encode($imagesUrl, JSON_UNESCAPED_UNICODE), //图片
                $this->supplierCommodity->skuCode          => $this->replaceUnnormalString($contents['goodsSKU']), //sku编码
                $this->supplierCommodity->name             => $contents['goodsName'], //商品名称
                $this->supplierCommodity->key              => $contents['goodsSKU'], //唯一标识 有些供应商需要2个编码下单
                $this->supplierCommodity->isHaveTaxRate    => $isHaveTaxRate, //是否含税 1含 0不含  是否含税根据字段price_type
                $this->supplierCommodity->taxRate          => bcdiv((string)$contents['tax'], '100', 4), //税率
                $this->supplierCommodity->upstreamSaleType => $upstreamSaleType, //上游的上下架状态 1上 0下
                $this->supplierCommodity->isFreeShipping   => 1, //是否包邮 1是 0否

            ],
            'stock' => $stock, //库存信息
            'other' => [
                'weight' => $contents['goodsUnit'] =='千克' ? $contents['grossWeight'] * 1000 : 0, //重量g 毛重
                // 'MarketingPrice' => reset($contents['skuList'])['marketPrice'], //市场价,
            ],
            'isDownBatchNo'=>$isDownBatchNo,
//            'isAutoDown'=>false,
        ];

    }

    /**
     * 商品id集合
     * @param $goodsList
     * @return array
     */
    public function getGoodsSkus($goodsList) {
        return array_column($goodsList, 'goodsSKU');
    }
}
